package com.rr.advisors;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClientMessageAggregator;
import org.springframework.ai.chat.client.ChatClientRequest;
import org.springframework.ai.chat.client.ChatClientResponse;
import org.springframework.ai.chat.client.advisor.api.CallAdvisor;
import org.springframework.ai.chat.client.advisor.api.CallAdvisorChain;
import org.springframework.ai.chat.client.advisor.api.StreamAdvisor;
import org.springframework.ai.chat.client.advisor.api.StreamAdvisorChain;
import reactor.core.publisher.Flux;

/**
 * 重写打印日志
 */
@Slf4j
public class MyLoggerAdvisor implements CallAdvisor , StreamAdvisor {
    private void before(ChatClientRequest request){
        log.info(request.prompt().getUserMessages().toString());
    };

    /**
     * 普通环绕
     * @param chatClientRequest 用户发的消息
     * @param callAdvisorChain ai回复的消息
     * @return
     */
    @Override
    public ChatClientResponse adviseCall(ChatClientRequest chatClientRequest, CallAdvisorChain callAdvisorChain) {
       //处理前置请求
        this.before(chatClientRequest);
        //调用链中下一个aop环绕
        ChatClientResponse response = callAdvisorChain.nextCall(chatClientRequest);
        //处理后置请求
        this.observAfter(response);
        return response;
    }

    private void observAfter(ChatClientResponse response) {

        log.info(response.chatResponse().getResult().getOutput().toString());
    }

    /**
     * 流式环绕
     * @param chatClientRequest 用户发的消息
     * @param streamAdvisorChain ai回复的消息
     * @return
     */
    @Override
    public Flux<ChatClientResponse> adviseStream(ChatClientRequest chatClientRequest, StreamAdvisorChain streamAdvisorChain) {
      this.before(chatClientRequest);
        Flux<ChatClientResponse> chatClientResponses = streamAdvisorChain.nextStream(chatClientRequest);
        return new ChatClientMessageAggregator().aggregateChatClientResponse(chatClientResponses, this::observAfter);
    }

    @Override
    public String getName() {
        return this.getClass().getName();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
